import React from "react";
import { useDispatch, useSelector } from "react-redux"
import { Link } from "react-router-dom";
import { PostAuthor } from "./PostAuthor";
import { TimeAgo } from "./TimeAgo";
import { selectAllPosts, fetchPosts } from "./postsSlices";
import { Spinner } from "../../components/Spinner";
import { useEffect } from "react";
import { ReactionButtons } from './ReactionButtons'

let PostExcerpt = ({post}) => {
  return (
    <article className="post-excerpt" key={post.id}>
      <h3>{post.title}</h3>
      <div>
        <PostAuthor authorId={post.user}/>
        <TimeAgo timestamp={post.date}/>
      </div>
      <p className="post-content">{post.content.substring(0,100)}</p>
      <Link to={`/posts/${post.id}`} className="button muted-button">
        View Post
      </Link>
      <Link to={`/editPosts/${post.id}`} className="button muted-button">
        Edit Post
      </Link>
      <ReactionButtons post={post}/>
    </article>
  )
}
PostExcerpt = React.memo(PostExcerpt) // ensure that the component inside of memo() only re-renders if the props have actually changed.

export const PostList = () => {
  const dispatch = useDispatch();

  const posts = useSelector(selectAllPosts);
  const postStatus = useSelector(state => state.posts.status)
  const error = useSelector(state => state.posts.error)

  useEffect(() => {
    if (postStatus === 'idle') {
      dispatch(fetchPosts())
    }
  }, [postStatus, dispatch])

  let content

  if (postStatus === 'loading') {
    content = <Spinner text="Loading..."/>
  } else if (postStatus === 'successed'){
    const orderedPosts = posts.slice().sort((a, b) => b.date.localeCompare(a.date))
    content = orderedPosts.map(post => (
      <PostExcerpt key={post.id} post={post}/>
    ))
  } else if (postStatus === 'failed') {
    content = <div>{error}</div>
  }

  return (
    <section className="posts-list">
      <h2>Posts</h2>
      {content}
    </section>
  )
}